package com.example.demo.handler;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 异常解决处理器
 * 当访问发生错误的时候，springSecurity自动调用
 * springSecurity想调用类中的方法，处理异常，必须从spring容器中获取对象
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {


    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException, ServletException {

//        设置响应状态
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
//        设置响应类型
        httpServletResponse.setContentType("text/html;charset=UTF-8");
//        设置响应输出
        httpServletResponse.getWriter().println("<span>权限不足，请联系管理员</span>");
//        刷新输出流的缓冲区
        httpServletResponse.getWriter().flush();

    }
}
